import matplotlib as mpl
from matplotlib.font_manager import FontProperties
import matplotlib.pyplot as plt

def get_macd_data(df_raw,fast_period=12,slow_period=26,signal_period=9):
    # df_raw['close'] -- 收盘价
    # 收盘价按照日期升序( df_raw['date'] )排列
    # 返回值都是 Series
    fast_ewm=df_raw['close'].ewm(span=fast_period).mean()
    slow_ewm=df_raw['close'].ewm(span=slow_period).mean()

    dif=fast_ewm-slow_ewm
    dea=dif.ewm(span=signal_period).mean()
    # 一般概念里，macd柱是 (dif-dea)*2，实际上只是为了扩大显示效果
    # 实测后发现，也可以不乘以2，效果也足够清楚了
    bar=(dif-dea)*2
   # 将bar 分成红绿柱分别导出数据，
   #目的是后续用matplotlib绘图时，能够分色绘制
    red_bar=bar[bar>=0]
    green_bar=bar[bar<0]
    return dif,dea,red_bar,green_bar

title_font=FontProperties(family='YouYuan',size=18)
mpl.rcParams['axes.unicode_minus']=False

def draw_macd(df_raw, dif, dea,
              red_bar, green_bar,
              canvas_w=1000, canvas_h=480,
              xtick_period=20,
              title=u'MACD'):
    dpi=72
    figsize=canvas_w/72,canvas_h/72
    plt.figure(figsize=figsize)

    p_dif=plt.plot(dif.index,dif.values)
    p_dea=plt.plot(dea.index,dea.values)
    plt.bar(red_bar.index, red_bar.values, color='#d62728')
    plt.bar(green_bar.index, green_bar.values, color='#889966')
    major_index=df_raw.index[df_raw.index%xtick_period==0]
    major_xtics=df_raw['date'][df_raw.index%xtick_period==0]
    plt.xticks(major_index,major_xtics)
    plt.legend((p_dif[0],p_dea[0]),[u'DIF',u'DEA'])
    plt.title(title,fontproperties=title_font)

    plt.show()